/**
 * @description 脚本加载
 * @param path -脚本地址
 * @param options -脚本属性
 * @returns promise
 */
function loadScript(path: string | string[], options = { async: false, defer: false }) {
  if (!path) return;

  return new Promise((resolve, reject) => {
    if (typeof path !== 'string') {
      if (Array.isArray(path)) {
        Promise.all(path.map((p) => loadScript(p, options)))
          .then(resolve)
          .catch(reject);

        return;
      }

      reject(new Error('Script 加载失败!'));
    }

    const script = document.createElement('script');

    script.src = path;
    script.async = !!options.async;
    script.defer = !!options.defer;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

/**
 * @description 资源加载
 * @param path -资源地址
 * @param options -脚本属性
 * @returns promise
 */
function loadLink(path: string | string[], options = { rel: 'stylesheet' }) {
  if (!path) return;

  return new Promise((resolve, reject) => {
    if (typeof path !== 'string') {
      if (Array.isArray(path)) {
        Promise.all(path.map((p) => loadLink(p, options)))
          .then(resolve)
          .catch(reject);

        return;
      }

      reject(new Error('Link 加载失败!'));
    }

    const link = document.createElement('link');

    link.href = path;
    link.rel = options.rel;
    link.onload = resolve;
    link.onerror = reject;
    document.head.appendChild(link);
  });
}

export { loadScript, loadLink };
